/*
 * Copyright (c) 2009 Johnny Mast
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#import "Blink.h"

@interface Blink (Private)
	-(void)initDefaults;
@end

@implementation Blink
@synthesize _BlinkImage;
@synthesize _animdelta;
@synthesize _direction;
@synthesize _repeatcount;
@synthesize _rounds;
@synthesize _frameTimer;
@synthesize _delay;


-(id)initWithImage:(Image*)image {
	_BlinkImage = image;
	[self initDefaults];
	return self;
}

-(BOOL)isBlinking {
	return (_direction != kBlink_Stopped);
}

-(void)setDelay:(float)miliseconds {
	_delay     = miliseconds;
	_animdelta = 0.1001f;
}

-(void)setRepeatCount:(NSInteger)repeatcount {
	_repeatcount = repeatcount;	
}

-(void)renderAtPoint:(CGPoint)point centerOfImage:(BOOL)centerOfImage {
	[_BlinkImage renderAtPoint:point centerOfImage:centerOfImage];
}

-(void)stop {
	_direction = kBlink_Stopped;
	_rounds = 0;
}

-(void)stopVisible {
	[self stop];
	[_BlinkImage setAlpha:1.0f];
}

-(void)stopInvisible {
	[self stop];
	[_BlinkImage setAlpha:0.0f];
}

-(void)update:(float)delta {
	float alpha = [_BlinkImage getAlpha];
	
	_frameTimer += delta;
	
	
	if (_frameTimer > _delay && [self isBlinking])
	{
		_frameTimer = 0;
		
		if (_repeatcount != -1 && _rounds == _repeatcount)
		{
			[self stopVisible];
			return;
			
		}
		
		switch (_direction) {
			case kBlink_Backwards:
				if (alpha < 0.0f)
				{
					_direction = kBlink_Forward;
					[_BlinkImage setAlpha:0.0f];
					break;
				} 
				alpha -= _animdelta;
				break;
				
			case kBlink_Forward:
				if (alpha > 1.0f)
				{
					_direction = kBlink_Backwards;
					_rounds ++;
					
					[_BlinkImage setAlpha:1.0f];
					break;
				} 
				alpha += _animdelta;
				break;
		}
		[_BlinkImage setAlpha:alpha];
	}
}

@end




@implementation Blink (Private)

-(void)initDefaults {
	_direction   = kBlink_Backwards;
	_repeatcount = -1;
	
	[self setDelay:0.05f];
}

@end